/**
 * Copyright (C) 2010-2016 eBusiness Information, Excilys Group
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed To in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.ohosannotations.internal.core.handler;

import com.helger.jcodemodel.JBlock;
import com.helger.jcodemodel.JInvocation;
import com.helger.jcodemodel.JSwitch;

import org.ohosannotations.ElementValidation;
import org.ohosannotations.OhosAnnotationsEnvironment;
import org.ohosannotations.helper.KeyCodeHelper;
import org.ohosannotations.helper.ValidatorParameterHelper;
import org.ohosannotations.holder.HasKeyEventCallbackMethods;

import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;

import static com.helger.jcodemodel.JExpr.TRUE;
import static com.helger.jcodemodel.JExpr.invoke;

/**
 * 抽象的关键事件处理程序
 *
 * @author dev
 * @since 2021-07-22
 */
public abstract class AbstractKeyEventHandler extends CoreBaseAnnotationHandler<HasKeyEventCallbackMethods> {
    /**
     * 注释的助手
     */
    protected final KeyCodeHelper annotationHelper;

    /**
     * 抽象的关键事件处理程序
     *
     * @param targetClass 目标类
     * @param environment 环境
     */
    public AbstractKeyEventHandler(Class<?> targetClass, OhosAnnotationsEnvironment environment) {
        super(targetClass, environment);
        this.annotationHelper = new KeyCodeHelper(environment, getTarget());
    }

    /**
     * validate
     *
     * @param element element
     * @param validation validation
     */
    @Override
    protected void validate(Element element, ElementValidation validation) {
        coreValidatorHelper.enclosingElementExtendsKeyEventCallback(element, validation);

        validatorHelper.isNotPrivate(element, validation);

        validatorHelper.doesntThrowException(element, validation);

        if (!annotationHelper.uniqueKeyCode(element, getTarget())) {
            validation.addError(element, "%s " + element.getSimpleName() + " keyCode is not unique");
        }

        ExecutableElement executableElement = (ExecutableElement) element;

        validatorHelper.returnTypeIsVoidOrBoolean(executableElement, validation);

        String[] paramTypes = getParamTypes();
        ValidatorParameterHelper.AnyOrderParamValidator param = validatorHelper.param.anyOrder();
        if (paramTypes.length > 0) {
            for (String paramType : paramTypes) {
                param.type(paramType).optional();
            }
            param.validate(executableElement, validation);
        }
    }

    /**
     * process
     *
     * @param element element
     * @param holder holder
     * @throws Exception 异常
     */
    @Override
    public void process(Element element, HasKeyEventCallbackMethods holder) throws Exception {
        String methodName = element.getSimpleName().toString();

        ExecutableElement executableElement = (ExecutableElement) element;
        TypeMirror returnType = executableElement.getReturnType();

        boolean returnMethodResult = returnType.getKind() != TypeKind.VOID;

        JSwitch switchBody = getSwitchBody(holder);

        int[] keyCodes = annotationHelper.extractKeyCode(element);
        for (int keyCode : keyCodes) {
            String keyCodeFieldName = annotationHelper.getFieldNameForKeyCode(keyCode);
            JBlock switchCaseBody = switchBody._case(getClasses().KEY_EVENT.staticRef(keyCodeFieldName)).body();

            JInvocation methodCall = invoke(methodName);

            if (returnMethodResult) {
                switchCaseBody._return(methodCall);
            } else {
                switchCaseBody.add(methodCall);
                switchCaseBody._return(TRUE);
            }

            passParametersToMethodCall(element, holder, methodCall);
        }
    }

    /**
     * getParamTypes
     *
     * @return getParamTypes
     */
    public abstract String[] getParamTypes();

    /**
     * getSwitchBody
     *
     * @param holder holder
     * @return holder
     */
    public abstract JSwitch getSwitchBody(HasKeyEventCallbackMethods holder);

    /**
     * passParametersToMethodCall
     *
     * @param element element
     * @param holder holder
     * @param methodCall methodCall
     */
    public abstract void passParametersToMethodCall(Element element,
    HasKeyEventCallbackMethods holder, JInvocation methodCall);
}
